//引入express模块
const express=require('express');
//引入连接池模块
const pool=require('../pool.js');
//console.log(pool);
//创建路由器对象
const r=express.Router();

//用户注册接口..http://127.0.0.1:3000/users/register
r.post('/register', (req, res) => {
	//console.log(md5('12345678'));
	// 获取用户名和密码信息
	let uname = req.body.uname;
	let upwd = req.body.upwd;
	//以username为条件进行查找操作，以保证用户名的唯一性
	let sql = 'SELECT COUNT(uid) AS count FROM wdm_user WHERE uname=?';
	pool.query(sql, [uname], (error, results) => {
	  console.log(results)
	  if (error) throw error;
	  let count = results[0].count;
	  if (count == 0) {
	    // 将用户的相关信息插入到数据表
	    sql = 'INSERT wdm_user(uname,upwd) VALUES(?,?)';
	    pool.query(sql, [uname, upwd], (error, results) => {
	      if (error) throw error;
	      res.send({ message: 'ok', code: 200 });
	    })
	  } else {
	    res.send({ message: 'user exists', code: 201 });
	  }
	});
      });
  //用户登陆接口..http://127.0.0.1:3000/users/login
  r.post('/login', (req, res) => {
	//获取用户名和密码信息
	let uname = req.body.uname;
	let upwd = req.body.upwd;
	// SQL语句
	let sql = 'SELECT uid,uname,nickname,phone,upwd FROM wdm_user WHERE uname=? AND upwd=?';
	pool.query(sql, [uname, upwd], (error, results) => {
	  if (error) throw error;
	  if(results.length == 0){ //登录失败
	    res.send({message:'login failed',code:201});
	  } else {           
	   // console.log(results)      //登录成功
	    res.send({message:'ok',code:200,result:results[0]});
	  }
	});
      
      });







//导出路由器对象
module.exports=r;